<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片区域数据-->
    <el-card>
      <!--警告区域-->
      <el-alert title="注意:只允许为第三级分类设置相关参数" type="warning"
                :closable="false" show-icon></el-alert>
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange" clearable></el-cascader>
        </el-col>
      </el-row>
      <!--tab标签区域-->
      <el-tabs v-model="activeName" @tab-click="tabHandleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isButtonDisabled" @click="addDialogVisible = true">添加参数</el-button>
          <!--表格数据-->
          <el-table
            :data="manyTableData"
            style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template v-slot="scope">
                <!--循环渲染tag标签-->
                <el-tag v-for="(item,i) in scope.row.attrVals" :key="i" closable  @close="handleClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="50px"></el-table-column>
            <el-table-column label="参数名称" prop="attrName"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attrId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isButtonDisabled"  @click="addDialogVisible = true">添加属性</el-button>

          <el-table
            :data="onlyTableData"
            style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag v-for="(item,i) in scope.row.attrVals" :key="i" closable @close="handleClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="50px"></el-table-column>
            <el-table-column label="属性名称" prop="attrName"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attrId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!--添加参数对话框-->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialogVisible"
      width="50%" @close="addDialogClose">
      <el-form ref="addAttributeFormRef" :model="addAttributeForm" label-width="80px" :rules="addAttributeFormRules">
        <el-form-item :label="titleText" prop="attrName">
          <el-input v-model="addAttributeForm.attrName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAttributeButton">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改参数对话框-->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editDialogVisible"
      width="50%" @close="editDialogClose">
      <el-form ref="editAttributeFormRef" :model="editAttributeForm" label-width="80px" :rules="editAttributeFormRules">
        <el-form-item :label="titleText" prop="attrName">
          <el-input v-model="editAttributeForm.attrName" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editAttributeButton">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
    export default {
        name: "Params",
      data(){
          return{
            //初始化加载列表数据保存
            cateList:[],
            cateProps:{
              expandTrigger:'hover',
              value:'catId',
              label:'catName',
              children:'children'
            },
            //选中保存的数据
            selectedKeys:[],
            //tab 默认的初始化页面
            activeName:'many',
            //动态参数列表数据
            manyTableData:[],
            //静态参数列表数据
            onlyTableData:[],
            //显示对话框显示和隐藏
            addDialogVisible:false,
            addAttributeForm:{
              attrName:'',
            },
            addAttributeFormRules:{
              attrName:[{required:true,message:'请输入参数名称',trigger:'blur'}]
            },
            editDialogVisible:false,
            editAttributeForm:{},
            editAttributeFormRules:{
              attrName:[{required:true,message:'请输入参数名称',trigger:'blur'}]
            },
          }
      },
      created() {
          this.getCateList();
      },
      methods:{
        async getCateList(){
          const {data:res} = await this.$axios.get("category");
          if(res.code !=200) {
            return this.$message.error("获取分类失败");
          }
          this.cateList = res.data.resultList;
        },
        //监听分类下拉框事件
        async handleChange(){
          //console.log(this.selectedKeys);
          if(this.selectedKeys.length != 3) {
            this.selectedKeys = [];
            return;
          }
          this.getParamsData();
        },
        //tab 事件处理事件
        tabHandleClick(){
          this.getParamsData();
        },
        //获取参数列表
        async getParamsData() {
          //没有选择三级节点则清空数据
          if(this.selectedKeys.length != 3){
            this.onlyTableData = [];
            this.manyTableData = [];
            this.selectedKeys = [];
            return;
          }
          const {data:res} = await this.$axios.get("attributeList/"+this.catId,{params:{attrSel:this.activeName}})
          if(res.code != 200){
            return this.$message.error("获取参数失败");
          }
          //console.log(res.data);
          res.data.forEach(item=>{
            item.attrVals = item.attrVals?item.attrVals.split(" "):[];
            //控制按钮显示和隐藏
            item.inputVisible = false;
              //控制文本框输入值
            item.inputValue = '';
          });
          console.log(res.data);
          if(this.activeName == 'many') {
            this.manyTableData = res.data;
          } else {
            this.onlyTableData = res.data;
          }
        },
        //监听添加对话框关闭事件
        addDialogClose(){
          this.$refs.addAttributeFormRef.resetFields();
        },
        //监听编辑对话框关闭事件
        editDialogClose(){
          this.editAttributeForm = {};
          this.$nextTick(()=>{
            this.$refs.editAttributeFormRef.resetFields();
          })

        },
        //监听保存参数事件
        addAttributeButton(){
          this.$refs.addAttributeFormRef.validate(async valid=>{
            if(!valid) return;

            const {data:res} = await this.$axios.post("add/attribute",
              'catId='+this.catId+'&attrName='+this.addAttributeForm.attrName+'&attrSel='+this.activeName);
            console.log(res);
            if(res.code != 200) {
              return this.$message.error("添加参数失败");
            }
            this.$message.success("添加参数成功");
            this.getParamsData();
            this.addDialogVisible = false;
          })
        },
        //监听编辑按钮事件
        showEditDialog(row){
          this.editAttributeForm = row;
          this.editDialogVisible = true;
        },
        //监听修改按钮提交事件
        editAttributeButton(){
          this.$refs.editAttributeFormRef.validate(async valid=>{
            if(!valid) return;
            const {data:res} = await this.$axios.put("update/attribute",
              'attrId='+this.editAttributeForm.attrId+'&attrName='+this.editAttributeForm.attrName);
            if(res.code != 200) {
              this.$message.error("修改失败")
            }
            this.$message.success("编辑成功");
            this.getParamsData();
            this.editDialogVisible = false;
          })
        },
        //监听删除分类事件
        async deleteParams(id){
          const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err=>err);
          if(confirmResult != 'confirm'){
              return this.$message.info("已取消操作");
          }
          const {data:res} = await this.$axios.delete("delete/attribute",{params:{attrId:id}});
          if(res.code != 200) {
              return this.$message.error("删除分类失败");
          }
          this.getParamsData();
          this.$message.success("删除分类成功");
        },
        //监听tag标签输入文本值后， 按 enter和失去焦点触发
        async handleInputConfirm(row){
          if(row.inputValue.trim().length == 0) {
            row.inputVisible = false;
            row.inputValue = '';
            return;
          }
          //不为空则新增标签
          row.attrVals.push(row.inputValue.trim());
          row.inputValue = '';
          row.inputVisible = false;
          //新增或修改可选值列表
          const {data:res} = await this.$axios.put("update/attrVals",
            'attrId='+row.attrId+'&attrVals='+row.attrVals.join(" "));
          if(res.code != 200) {
            return this.$message.error("修改失败")
          }
          this.$message.success("修改成功");
        },
        //tag标签点击事件
        showInput(row){
          row.inputVisible = true;
          //让文本框自动获取焦点
          //$nextTick 方法作用，页面元素重新渲染后，才会指定回调函数中的代码
          this.$nextTick(()=> {
            this.$refs.saveTagInput.$refs.input.focus();
          });
        },
        //监听tag 删除标签是触发事件
        async handleClose(i,row){
          row.attrVals.splice(i,1);
          //新增或修改可选值列表
          const {data:res} = await this.$axios.put("update/attrVals",
            'attrId='+row.attrId+'&attrVals='+row.attrVals.join(" "));
          if(res.code != 200) {
            return this.$message.error("修改失败")
          }
          this.$message.success("修改成功");
        }
      },
      //计算属性方法
      computed:{
        //是否选中三级分类，如果不是禁用，否则开启
        isButtonDisabled(){
          if(this.selectedKeys.length == 3) {
              return false;
          } else {
            return true;
          }
        },
        //当前选中三级分类id
        catId(){
          if(this.selectedKeys.length == 3) {
            return this.selectedKeys[2];
          }
          return null;
        },
        //计算标题属性
        titleText(){
          if(this.activeName == 'many') {
            return '动态参数';
          } else {
            return '属性参数';
          }
        }
      }
    }
</script>

<style scoped>
.el-card{
  margin-top: 15px;
}
  .el-row{
    margin-top: 15px;
  }
  .el-cascader{
     width: 300px;
  }
  .el-tabs{
    margin-top: 15px;
  }
  .el-table{
    margin-top: 15px;
  }
  .el-tag{
    margin: 15px;
  }
.input-new-tag {
  width: 80px;
}
</style>
